<?php
class PersonalSponsorPage extends MemberPage {

    private static $db = array(
    );

    private static $has_one = array(
    );

}
class PersonalSponsorPage_Controller extends MemberPage_Controller {

    /**
     * An array of actions that can be accessed via a request. Each array element should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * array (
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this action
     *     'action' => '->checkAction' // you can only access this action if $this->checkAction() returns true
     * );
     * </code>
     *
     * @var array
     */
    private static $allowed_actions = array (
    	'Form',
        'root_data',
        'load_data',
        'member_detail'
    );

    function init() {
        parent::init();
    }

	function index(){
		Requirements::javascript(THIRDPARTY_DIR.'/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
		Requirements::add_i18n_javascript('network/javascript/lang');
        Requirements::javascript('network/thirdparty/jstree/jstree.min.js');
		Requirements::css('network/thirdparty/jstree/themes/default/style.min.css');
        Requirements::javascript("network/javascript/PersonalSponsorPage.min.js");
        Requirements::css('network/css/PersonalSponsorPage.css');
		return $this->renderWith(array('PersonalSponsorPage_index', 'PersonalSponsorPage', 'MemberPage', 'MemberOverviewPage', 'MemberAreaPage', 'Page', 'Controller'));
	}
    
    function load_data(){
        if($this->request->getVar('operation') && method_exists($this, $this->request->getVar('operation'))) {
            $this->response->addHeader("Content-Type", "application/json; charset=utf-8");
            $this->response->addHeader("Pragma", "no-cache");
            $this->response->addHeader("Cache-Control", "no-cache, must-revalidate");
            $this->response->setStatusCode(200);
            return $this->{$this->request->getVar('operation')}($this->request->getVar('id'));
        }
        
        $this->response->setStatusCode(404);
    }
	
	function Check($username){
		$valid = false;
		$sponsor = Sponsor::get()->find('MemberID', (int)$this->CurrentMember()->ID);
		if($sponsor && $username){
			$valid = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $sponsor->NLeft)->filter('NRight:LessThanOrEqual', $sponsor->NRight)->filter('Member.Username', $username)->count();
		}
		
		if($valid){
			$data = array(
				'result' => 'success'
	        );
		}
		else{
			$data = array(
				'result' => 'error',
	            'msg' => _t('NetworkAdmin.INVALID_MEMBER', 'Invalid member')
	        );
		}

        return Convert::array2json($data);
	}
    
    function Search($username){
        $sponsor = Sponsor::get()->find('MemberID', (int)$this->CurrentMember()->ID);
        $data = array();
		$matchedDownlines = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $sponsor->NLeft)->filter('NRight:LessThanOrEqual', $sponsor->NRight)->filter('Member.Username:PartialMatch', $username);
		if(!$matchedDownlines){
			return Convert::array2json(array());
		}
		
		$filter = array();
		foreach($matchedDownlines as $item){
			$filter[] = " (Sponsor.NLeft < ".(int)$item->NLeft." AND Sponsor.NRight > ".(int)$item->NRight.") ";
		}
		
		$select = array(
			"`ID`"
		);
		$from = array(
			"`Sponsor`"
		);
		$where = $filter;
		$orderby = '';

		$query = new SQLQuery($select, $from, $where, $orderby);
		$query->setDistinct(true);
		$query->setConnective('OR');
		$result = $query->execute();
		$data = array();
		while($item = $result->next()) { $data[] = "node_".$item['ID']; }
        return Convert::array2json($data);
    }
	
	function GetRoot($username){
		$sponsor = Sponsor::get()->find('MemberID', (int)$this->CurrentMember()->ID);
		$root_id = $sponsor ? $sponsor->ID : 0;
		if($sponsor && $username){
			$sponsor = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $sponsor->NLeft)->filter('NRight:LessThanOrEqual', $sponsor->NRight)->filter('Member.Username', $username)->first();
			$root_id = $sponsor ? $sponsor->ID : 0;
		}
		
		if($root_id){
			$data = array(
				'result' => 'success',
	            'root' => array_merge(Sponsor::tree_node_v3($root_id), array('state' => array('opened' => true)))
	        );
		}
		else{
			$data = array(
				'result' => 'error',
	            'msg' => _t('NetworkAdmin.INVALID_MEMBER', 'Invalid member')
	        );
		}

        return Convert::array2json($data);
    }
    
    function GetChildren($id){
    	$obj = Sponsor::get()->find('MemberID', (int)$this->CurrentMember()->ID);
        $sponsor = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $obj->NLeft)->filter('NRight:LessThanOrEqual', $obj->NRight)->byID((int)$id);
        if($sponsor){
            $result = array();
            $level = $sponsor->NLevel + 1;
            $children = $sponsor->ChildBranch("NLevel = " . $level);
            foreach($children as $child){
                $result[] = Sponsor::tree_node_v3($child->ID);
            }
			
			$data = array(
				'result' => 'success',
	            'root' => $result
	        );
        }
		else{
			$data = array(
				'result' => 'error',
	            'msg' => _t('NetworkAdmin.INVALID_MEMBER', 'Invalid member')
	        );
		}
		
		return Convert::array2json($data);
    }
    
    function member_detail(){
        $current_sponsor = Sponsor::get()->find('MemberID', (int)$this->CurrentMember()->ID);
        $sponsor = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $current_sponsor->NLeft)->filter('NRight:LessThanOrEqual', $current_sponsor->NRight)->find('MemberID', (int)$this->request->getVar('id'));
        if($sponsor){
            $member = Member::get()->byID($sponsor->MemberID);
            $template = new SSViewer('PersonalSponsorPage_member_details');
	        $template->includeRequirements(false);
	        return $template->process($this->customise(array('Member' => $member, 'ShowSponsor' => Config::inst()->get('Sponsor', 'show_sponsor'))));
        }
        
        return _t('PersonalSponsorPage.INVALID_MEMBER', 'Invalid member');
    }
}